<template>
  <div class="login-wrap">
    <el-image class="bg1" :src="bg1" fit="fill"></el-image>
    <el-image class="bg2" :src="bg2" fit="fill"></el-image>
    <div class="icon-wrap">
      <div class="title">{{ title }}</div>
      <el-image class="icon" :src="icon" fit="contain"></el-image>
    </div>
    <div class="box-wrap">
      <div class="title">登录</div>
      <el-form
        ref="formRef"
        :model="ruleForm"
        :rules="rules"
        label-position="top"
        label-width="120px"
        class="demo-ruleForm"
        :size="'default'"
      >
        <el-form-item label="" prop="userName">
          <el-input
            v-model.trim="ruleForm.userName"
            placeholder="请输入您的账号"
            clearable
          />
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input
            v-model.trim="ruleForm.password"
            placeholder="请输入您的密码"
            show-password
            clearable
          />
        </el-form-item>
        <el-form-item label="" prop="smsCode" class="code-wrap">
          <el-input
            v-model.trim="ruleForm.smsCode"
            placeholder="请输入验证码"
            clearable
          />
          <el-button
            type="primary"
            class="bnt-code"
            :disabled="codeObj.count < 120"
            @click="clickCode"
            >{{ codeObj.codeName }}</el-button
          >
        </el-form-item>
      </el-form>
      <div class="pws-wrap">
        <el-switch v-model="savePws" inactive-color="#d4dbf5"></el-switch>
        <div class="text">记住密码</div>
      </div>
      <el-button type="primary" class="bnt-login" @click="clickLogin"
        >登录系统</el-button
      >
    </div>
    <!-- 备案信息 -->
    <div v-if="icp" class="beian-wrap">
      <a class="icp text" href="https://beian.miit.gov.cn/" target="_blank">{{
        icp
      }}</a>
      |
      <div class="text">版权所有 @ {{ company }}</div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import type { FormRules, FormInstance } from 'element-plus';
import bg1 from '@/assets/images/login/bg1.png';
import bg2 from '@/assets/images/login/bg2.png';
import icon from '@/assets/images/login/img.png';
import {
  sendSmsCode,
  login,
  queryMenuTree,
  queryButtonList,
} from '@/service/apis/api';
import { getMd5 } from '@/utils/utils';

const icp = import.meta.env.VITE_ENV_ICP;
const company = import.meta.env.VITE_ENV_COMPANY;

const router = useRouter();
const formRef = ref<FormInstance>();

const title = document.title;

const ruleForm = reactive({
  userName: '',
  password: '',
  smsCode: '',
});

const rules = reactive<FormRules>({
  userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
});

// 记住账号密码
let savePws = ref(false);
const saveLogin = window.localStorage.getItem('login');
if (saveLogin) {
  savePws.value = true;
  const obj = JSON.parse(saveLogin);
  ruleForm.userName = obj.userName;
  ruleForm.password = obj.password;
}

// 获取验证码
const codeObj = reactive({
  codeName: '获取验证码',
  disabled: false,
  count: 120,
  timeout: 0,
});
const clickCode = () => {
  if (codeObj.count < 120) {
    return;
  }
  if (ruleForm.userName) {
    sendSmsCode({ userName: ruleForm.userName }).then((res: any) => {
      ElMessage({
        showClose: true,
        message: res.msg,
        type: 'success',
      });
      codeObj.timeout = setInterval(() => {
        if (codeObj.count < 1) {
          codeObj.disabled = false;
          codeObj.codeName = '重新获取';
          codeObj.count = 120;
          clearInterval(codeObj.timeout);
        } else {
          codeObj.disabled = true;
          codeObj.codeName = `${codeObj.count--}s后重发`;
        }
      }, 1000);
    });
  } else {
    formRef.value?.validateField('userName');
  }
};

// 登录
const clickLogin = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (valid) {
      const from = {
        userName: ruleForm.userName,
        password: getMd5(ruleForm.password),
        smsCode: ruleForm.smsCode,
      };
      login(from).then((res: any) => {
        console.log('login---', res);
        if (res) {
          window.localStorage.removeItem('city-data');
          window.localStorage.removeItem('region-data');
          window.localStorage.removeItem('region-code');
          window.localStorage.removeItem('orgName');
          window.localStorage.setItem('token', res.token);
          window.localStorage.setItem('accountName', res.account.accountName);
          window.localStorage.setItem('accountCode', res.account.accountCode);
          window.localStorage.setItem('accountId', res.account.accountId);
          if (
            res.account.channelId &&
            res.account.channelId !== '-1' &&
            res.account.channelId !== '-100'
          ) {
            window.localStorage.setItem('channelId', res.account.channelId);
          } else {
            window.localStorage.removeItem('channelId');
          }
          if (
            res.account.operatorId &&
            res.account.operatorId !== '-1' &&
            res.account.operatorId !== '-100'
          ) {
            window.localStorage.setItem('orgId', res.account.operatorId);
          } else {
            window.localStorage.removeItem('orgId');
          }
          Promise.all([queryMenuTree(), queryButtonList()]).then(
            ([menu, btn]) => {
              console.log('menu----', menu);
              console.log('btn----', btn);
              if (menu) {
                if (savePws.value) {
                  // 记住密码
                  const obj = {
                    userName: ruleForm.userName,
                    password: ruleForm.password,
                  };
                  window.localStorage.setItem('login', JSON.stringify(obj));
                } else {
                  window.localStorage.removeItem('login');
                }
                window.localStorage.setItem('menuTree', JSON.stringify(menu));
                window.localStorage.setItem(
                  'btnList',
                  btn ? JSON.stringify(btn) : ''
                );
                router.push({
                  name: 'welcome',
                });
              } else {
                ElMessageBox.alert(
                  '此账号没有菜单权限，请联系管理员！',
                  '提示',
                  {
                    confirmButtonText: '确认',
                    type: 'warning',
                  }
                );
              }
            }
          );
          // queryMenuTree({}).then((res1: any) => {
          //   if (res1) {
          //     if (savePws.value) {
          //       // 记住密码
          //       const obj = {
          //         userName: ruleForm.userName,
          //         password: ruleForm.password,
          //       };
          //       window.localStorage.setItem('login', obj.toString());
          //     } else {
          //       window.localStorage.removeItem('login');
          //     }
          //     window.localStorage.setItem('menuTree', res1.toString());
          //     router.push({
          //       name: 'welcome',
          //     });
          //   } else {
          //     ElMessageBox.alert('此账号没有菜单权限，请联系管理员！', '提示', {
          //       confirmButtonText: '确认',
          //       type: 'warning',
          //     });
          //   }
          // });
        }
      });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const keydownEvent = () => {
  document.onkeydown = (e: any) => {
    if (e.keyCode === 13 || e.keyCode === 32) {
      clickLogin();
    }
  };
};

onMounted(() => {
  window.addEventListener('keydown', keydownEvent, true);
});

onUnmounted(() => {
  window.removeEventListener('keydown', keydownEvent, true);
});
</script>

<style lang="scss" scoped>
.login-wrap {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  position: relative;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  min-width: 1000px;
  min-height: 555.56px;
  overflow: hidden;

  .bg1 {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 78.5%;
    min-height: 555.56px;
  }
  .bg2 {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 67.8%;
    min-height: 555.56px;
  }

  .icon-wrap {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: absolute;
    left: 12.8%;
    width: 32.8%;
    min-width: 328px;

    .title {
      position: relative;
      font-size: 32px;
      color: #fff;
      font-weight: bold;
      text-align: center;
      margin-bottom: 10%;
    }
    .icon {
      position: relative;
      width: 32.8%;
      min-width: 328px;
      min-height: 302px;
    }
  }

  .box-wrap {
    display: flex;
    flex-direction: column;
    position: relative;
    width: 400px;
    height: 376px;
    margin-right: 7%;
    padding: 70px 40px;
    background-color: #fff;
    border-radius: 16px;
    z-index: 2;
    color: #000;

    .title {
      margin-bottom: 25px;
      line-height: 36px;
      font-size: 28px;
    }

    .pws-wrap {
      display: flex;
      align-items: center;
      height: 24px;
      .text {
        margin-left: 8px;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.4);
      }
    }

    .bnt-login {
      height: 44px;
      margin-top: 27px;
      font-size: 16px;
      font-weight: bold;
    }
  }
  .code-wrap {
    .el-input {
      width: 70%;
    }
    :deep(.el-input__wrapper) {
      border-top-right-radius: 0;
      border-bottom-right-radius: 0;
    }
    .bnt-code {
      width: 30%;
      height: 46px;
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
    :deep(.el-button--default) {
      --el-button-border-color: var(--el-color-primary);
      --el-button-text-color: #fff;
      --el-button-active-text-color: #fff;
      --el-button-hover-text-color: #fff;
      --el-button-active-bg-color: var(--el-color-primary-dark-2);
      --el-button-bg-color: var(--el-color-primary);
      --el-button-hover-bg-color: var(--el-color-primary);
      --el-button-hover-border-color: #c4c4c4;
      &:hover {
        --el-button-hover-bg-color: var(--el-color-primary-light-3);
      }
    }
  }
}

:deep(.el-form-item__label) {
  line-height: 24px;
  font-size: 16px;
  color: #000;
}
:deep(.el-input__wrapper) {
  height: 44px;
  border-color: #ededed;
  border-radius: 10px;
  box-shadow: 0 0 0 1px #ededed inset;
  font-size: 16px;
}
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color) inset;
}
:deep(.el-form-item--default) {
  margin-bottom: 27px;
}
:deep(.el-switch__core) {
  min-width: 36px;
}

.beian-wrap {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: absolute;
  width: 100%;
  bottom: 0;
  padding-right: 20px;
  line-height: 22px;
  color: rgba($color: #fff, $alpha: 0.6);
  font-size: 12px;

  .text {
    margin: 0 5px;
    color: #ccc;
    font-size: 12px;
  }
  .icp {
    cursor: pointer;
  }
}
</style>